package com.flow.framework.module.call.rpc.decoder;

import com.flow.framework.common.stream.BatchProcessInputStream;
import com.flow.framework.common.stream.handler.BatchReturnProcessHandler;
import com.flow.framework.common.util.verify.VerifyUtil;
import com.flow.framework.module.call.rpc.proto.CustomizationVoid;
import com.flow.framework.module.call.rpc.util.FeignUtil;
import feign.FeignException;
import feign.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 在ResponseEntityDecoder的基础上新增对body和框架Response的字符串的反序列化
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/2/19
 */
@Slf4j
public class CustomizationRpcSuccessDecoder extends ResponseEntityDecoder {

    /**
     * 响应记录时的最大body长度
     */
    private static final int MAX_BODY_BYTES_LENGTH = 16384;

    /**
     * 批量处理输入流的大小
     */
    private static final int BATCH_PROCESS_INPUT_STREAM_SIZE = 8192;

    /**
     * 批量处理输入流的次数（缓存body数据，用于记录响应字符串）
     */
    private static final int CACHE_MAX_COUNT = 2;

    public CustomizationRpcSuccessDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
        super(new SpringDecoder(messageConverters));
    }

    /**
     * @inheritDoc
     */
    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        String url = response.request().url();
        Map<String, Collection<String>> headers = response.headers();
        boolean innerRequest = RpcHelper.isInnerRequest(response);
        com.flow.framework.core.response.Response<String> frameworkResponse = null;
        if (innerRequest) {
            frameworkResponse = RpcHelper.getFrameworkResponse(headers, url);
        }
        List<byte[]> bytesList = new ArrayList<>();
        Response finalResponse = response;
        AtomicInteger bodyCacheLength = new AtomicInteger(0);
        boolean isTextBody = RpcHelper.isTextBody(headers);
        if (isTextBody) {
            // 如果方法定义返回值为void并且被框架替换为CustomizationVoid后，判断响应的body和框架Response是否响应成功
            if (CustomizationVoid.class == type) {
                byte[] responseByteBody = FeignUtil.getResponseByteBody(response, MAX_BODY_BYTES_LENGTH);
                String stringBody = new String(responseByteBody, FeignUtil.getResponseCharset(headers));
                if (responseByteBody.length == MAX_BODY_BYTES_LENGTH) {
                    stringBody = stringBody + "..., has more content";
                }
                if (innerRequest && RpcHelper.isResponseFailed(frameworkResponse)) {
                    log.error("remote procedure call error, response byte body is error, url:{}, body : {}", url, stringBody);
                    RpcHelper.throwExceptionByFrameworkResponse(frameworkResponse);
                }
                if (VerifyUtil.isEmpty(stringBody)) {
                    return null;
                }
                log.error("remote procedure call error, required response byte body is error, url:{}, body : {}", url, stringBody);
                RpcHelper.throwExceptionByFrameworkResponse(frameworkResponse);
            }
            BatchProcessInputStream batchProcessInputStream = new BatchProcessInputStream(response.body().asInputStream(), new BatchReturnProcessHandler() {
                private int cacheCount = 0;

                @Override
                public byte[] process(byte[] buffer) {
                    if (cacheCount < CACHE_MAX_COUNT) {
                        bytesList.add(buffer);
                        bodyCacheLength.getAndAdd(buffer.length);
                        cacheCount++;
                    }
                    return buffer;
                }

                @Override
                public int getBatchSize() {
                    return BATCH_PROCESS_INPUT_STREAM_SIZE;
                }
            });
            finalResponse = response.toBuilder().body(batchProcessInputStream, response.body().length()).build();
        }

        Object protoResponse = null;
        try {
            protoResponse = super.decode(finalResponse, type);
        } catch (Exception e) {
            errorLog(isTextBody, bodyCacheLength, bytesList, response);
            log.error("remote procedure call error.", e);
            RpcHelper.throwExceptionByFrameworkResponse(frameworkResponse);
        }

        if (innerRequest && RpcHelper.isResponseFailed(frameworkResponse)) {
            errorLog(isTextBody, bodyCacheLength, bytesList, response);
            RpcHelper.throwExceptionByFrameworkResponse(frameworkResponse);
        }

        // 如果不是框架定义的Response，则直接返回，不做任何处理
        if (!(protoResponse instanceof com.flow.framework.core.response.Response)) {
            return protoResponse;
        }
        if (RpcHelper.isResponseFailed((com.flow.framework.core.response.Response) protoResponse)) {
            errorLog(isTextBody, bodyCacheLength, bytesList, response);
            RpcHelper.throwExceptionByFrameworkResponse(frameworkResponse);
        }
        return protoResponse;
    }

    private void errorLog(boolean isText, AtomicInteger bodyCacheLength, List<byte[]> bytesList, Response response) {
        int length = bodyCacheLength.get();
        if (length == 0) {
            log.error("remote procedure call error, response byte body is error, url:{}", response.request().url());
        }
        if (!isText) {
            log.error("remote procedure call error, response byte body is error, url:{}", response.request().url());
        }
        byte[] results = new byte[length];
        int destPos = 0;
        for (byte[] bytes : bytesList) {
            int dataLen = bytes.length;
            System.arraycopy(bytes, 0, results, destPos, dataLen);
            destPos += dataLen;
        }
        String stringBody = new String(results, FeignUtil.getResponseCharset(response.headers()));
        if (length == MAX_BODY_BYTES_LENGTH) {
            stringBody = stringBody + "..., has more content";
        }
        log.error("remote procedure call error, response byte body is error, url: {}, body: {}", response.request().url(), stringBody);
    }
}
